<template>
  <el-scrollbar
    v-show="show && showMembers.length"
    ref="scrollBox"
    class="group-member-choose"
    :style="{ left: pos.x + 'px', top: pos.y - 300 + 'px' }"
  >
    <div v-for="(member, idx) in showMembers" :key="member.id">
      <chat-group-member
        :member="member"
        :height="40"
        :active="activeIdx === idx"
        @click="onSelectMember(member)"
      ></chat-group-member>
    </div>
  </el-scrollbar>
</template>

<script setup name="chatAtBox">
import { ref, computed, watch, toRefs } from "vue";
import { useUserStore } from "@/store/userStore";
import { useChatStore } from "@/store/chatStore";
import ChatGroupMember from "./chatGroupMember.vue";
import GroupApi from "@/api/GroupApi";
import { ElMessage } from "element-plus";

// 定义 Props
const props = defineProps({
  searchText: {
    type: String,
    default: "",
  },
  ownerId: {
    type: String,
    default: () => "",
  },
  members: {
    type: Array,
    default: () => [],
  },
});
const { searchText, ownerId, members } = toRefs(props);
// 定义响应式变量
const show = ref(false);
const pos = ref({ x: 0, y: 0 });
const activeIdx = ref(0);
const showMembers = ref([]);
const scrollBoxRef = ref(null);

const userStore = useUserStore();
const chatStore = useChatStore();

// 初始化方法
const init = () => {
  const scrollBox = scrollBoxRef.value?.wrap;
  if (scrollBox) {
    scrollBox.scrollTop = 0;
  }
  showMembers.value = [];
  const userId = userStore.user.id;
  const name = "全体成员";

  // 如果是群主并且搜索匹配
  console.log(
    "ownerId",
    ownerId.value,
    "userId",
    userId,
    "name",
    name,
    "searchText",
    searchText.value,
    "members",
    members.value,
  );
  // @所有人 先隐藏
  // if (ownerId.value === userId && name.startsWith(searchText.value)) {
  //   showMembers.value.push({
  //     userId: -1,
  //     nickName: name,
  //   });
  // }

  // 遍历成员，筛选符合条件的成员
  members.value.forEach((m) => {
    if (m.id !== userId && m.nickName.startsWith(searchText.value)) {
      showMembers.value.push(m);
    }
  });
  console.log("要展示的用户列", showMembers.value);

  // 设置激活的索引
  activeIdx.value = showMembers.value.length > 0 ? 0 : -1;
};

// 打开选择框
const open = (position) => {
  console.log("打开选择框", position, "showMembers", showMembers.value);
  let userList = [];
  if (members.value.length === 0) {
    const chatInfo = chatStore.getChatInfo();
    console.log("当前房间信息", chatInfo);

    GroupApi.users(chatInfo.id)
      .then((res) => {
        if (res) {
          userList = res.data.map((item) => {
            return {
              id: item.userId,
              name: item.userName,
              avatar: item.avatar,
              nickName: item.nickName,
            };
          });
          members.value = userList;
          chatStore.saveChatUsers(chatInfo.id, userList);
        }
      })
      .catch((err) => {
        ElMessage.error(err.message);
      });
  } else {
    show.value = true;
    pos.value = position;
    init();
  }
};

// 关闭选择框
const close = () => {
  show.value = false;
};

// 向上移动选择
const moveUp = () => {
  if (activeIdx.value > 0) {
    activeIdx.value--;
    scrollToActive();
  }
};

// 向下移动选择
const moveDown = () => {
  if (activeIdx.value < showMembers.value.length - 1) {
    activeIdx.value++;
    scrollToActive();
  }
};

// 选择当前成员
const select = () => {
  if (activeIdx.value >= 0) {
    onSelectMember(showMembers.value[activeIdx.value]);
  }
  close();
};

// 滚动到激活的成员
const scrollToActive = () => {
  const scrollBox = scrollBoxRef.value?.wrap;
  if (!scrollBox) return;

  if (activeIdx.value * 35 - scrollBox.clientHeight > scrollBox.scrollTop) {
    scrollBox.scrollTop += 140;
    if (scrollBox.scrollTop > scrollBox.scrollHeight) {
      scrollBox.scrollTop = scrollBox.scrollHeight;
    }
  }
  if (activeIdx.value * 35 < scrollBox.scrollTop) {
    scrollBox.scrollTop -= 140;
    if (scrollBox.scrollTop < 0) {
      scrollBox.scrollTop = 0;
    }
  }
};

// 选择成员时触发
const emit = defineEmits(["select"]);
const onSelectMember = (member) => {
  emit("select", member);
  show.value = false;
};

// 是否为群主
const isOwner = computed(() => {
  return userStore.userInfo.id === ownerId.value;
});

// 监听搜索文本变化
watch(
  () => searchText.value,
  () => {
    init();
  },
);
defineExpose({
  open,
  close,
  moveUp,
  moveDown,
  select,
});
</script>

<style scoped lang="scss">
.group-member-choose {
  position: fixed;
  width: 200px;
  height: 300px;
  background-color: #fff;
  box-shadow: var(--im-box-shadow);
}
</style>
